package com.onec.service.auth.controller.exception;

import com.onec.service.api.dto.response.BaseResponse;
import com.onec.service.api.enums.ResultCodeEnum;
import com.onec.service.api.exception.BaseException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.oauth2.common.exceptions.InvalidGrantException;
import org.springframework.security.oauth2.common.exceptions.UnauthorizedClientException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

;

/**
 * spring 配置全局异常:
 * 配置该异常处理时：不可使用try-catch 捕获异常：
 *
 * @author ONEC
 */
@Slf4j
@RestControllerAdvice(basePackages = "com.onec.service.auth.controller")
public class ExceptionHandlerControllerAdvice {

    /**
     * 处理产品系统异常
     *
     * @param e
     * @return
     */
    @ExceptionHandler(value = Exception.class)
    public BaseResponse handlerException(Exception e) {
        e.printStackTrace();
        return BaseResponse.error(ResultCodeEnum.SERVER_ERROR);
    }

    /**
     * 处理自定义异常（controller and service）
     *
     * @param e
     * @return
     */
    @ExceptionHandler(value = BaseException.class)
    public BaseResponse handlerBaseException(BaseException e) {
        e.printStackTrace();
        return BaseResponse.error(e);
    }

    /**
     * 处理自定义异常（controller and service）
     *
     * @param e
     * @return
     */
    @ExceptionHandler(value = UnauthorizedClientException.class)
    public BaseResponse handlerUnauthorized(UnauthorizedClientException e) {
        e.printStackTrace();
        return BaseResponse.error(ResultCodeEnum.UNAUTHORIZED);
    }


    /**
     * 用户名和密码异常
     *
     * @param e
     * @return
     */
    @ExceptionHandler(InvalidGrantException.class)
    public BaseResponse handleInvalidGrantException(InvalidGrantException e) {
        return BaseResponse.error(ResultCodeEnum.USERNAME_OR_PASSWORD_ERROR);
    }

    /**
     * 账户异常(禁用、锁定、过期)
     *
     * @param e
     * @return
     */
    @ExceptionHandler({InternalAuthenticationServiceException.class})
    public BaseResponse handleInternalAuthenticationServiceException(InternalAuthenticationServiceException e) {
        return BaseResponse.error(ResultCodeEnum.USER_ACCESS_LOCK);
    }
}
